package com.ag.zhh.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ag.bean.TbDeptType;
import com.ag.zhh.vo.UserDept;
import com.ag.zhh.vo.UserDeptContact;

//用户部门表的dao
public class UserDeptDAO extends HibernateDaoSupport{
	private static final Log log = LogFactory.getLog(DeptDAO.class);

	protected void initDao() {
		// do nothing
	}

	public void setDeptDIfOnly(List<String> DIds) throws Exception {
		accessDeptDIf(DIds, 1);
	}

	public void resetDeptDIfOnly(List<String> DIds) throws Exception {
		accessDeptDIf(DIds, 0);
	}

	

	public List<UserDept> findByDIf(int DIf) throws Exception {
		Session session = null;
		List<UserDept> list = null;
		try {
			session = this.getSessionFactory().openSession();

			Query query = session.createQuery("from UserDept where udIf=?");
			query.setInteger(0, DIf);
			list = query.list();
		} catch (Exception e) {
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
			
		}System.out.println("********长度：**********"+list.size());
		return list;
	}

	public List<UserDept> findByDeptType(TbDeptType type) throws Exception {
		Session session = null;
		List<UserDept> list = null;
		// TbDeptTypeDAO typeDao = new

		try {
			session = this.getSessionFactory().openSession();

			System.out.println("**********************************************");
			Query query = session.createQuery("from UserDept u where u.tbDeptType=:deptType and (a=null or a='0')");
			query.setEntity("deptType", type);
			list = query.list();
			System.out.println("***************************"+list.size()+"*******");
			for(UserDept d:list)
			{
				System.out.println(d.getUdId()+"  "+d.getUdName());
			}
			
		} catch (Exception e) {
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
			
		}
		return list;
	}

	public List<UserDept> findByDeptTypes(List<TbDeptType> types) throws Exception {
		Session session = null;
		List<UserDept> list = null;
		// TbDeptTypeDAO typeDao = new
		session = this.getSessionFactory().openSession();
		try {
			// Transaction ts = session.beginTransaction();

			//Criteria criteria = session.createCriteria(Dept.class);
			//criteria.add(Restrictions.in("tbDeptType", types));
			//criteria.addOrder(Order.asc("DId"));
			//list = criteria.list();
			// ts.commit();
			Query query = session.createQuery("from UserDept d where d.tbDeptType.dtId in(:deptType)");
			//System.out.println(types.size());
			List<String> typesId = new ArrayList<String>();
			for(TbDeptType deptType:types) {
				//System.out.println("页数");
				typesId.add(deptType.getDtId());
				//System.out.println(deptType.getDtId());
			}
			//for(String str:typesId ){
			//	System.out.println(str);
			//}
			//typesId.add("0001");
			//typesId.add("0002");
			query.setParameterList("deptType", typesId);
			list = query.list();
			
		} catch (Exception e) {
			throw e;
		} finally {
			if (session != null)
				session.close();
			
		}
		return list;
	}

	public void saveOrUpdateDept(UserDept dept) {
		log.debug("saving UserDept instance");
		//Session session = this.getSessionFactory().openSession();
	//	Transaction tx = session.beginTransaction();
		try {
			getHibernateTemplate().saveOrUpdate(dept);
		//	session.saveOrUpdate(dept);
			System.out.println("部门的dao：部门id："+dept.getUdId()+"  部门名："+dept.getUdName()+" 部门类型："+dept.getTbDeptType().getDtId()+" 手机："+dept.getUdPhone()+" 部门电话："+dept.getUdTel()+" 部门传真："+dept.getUdFax());
		//	tx.commit();
		//	log.debug("save successful");
		} catch (Exception e) {
	//		tx.rollback();
		//	log.error("save failed", e);
			e.printStackTrace();
		}finally{
//			if(tx != null){
//				tx.
//			}
		}
		//session.close();
	}
	
	public void deleteDept(UserDept dept) {
		log.debug("saving UserDept instance");
		try {
			getHibernateTemplate().delete(dept);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}
	public void deleteDept(String  deptId) {
		log.debug("delete UserDept instance");
		Session session = this.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		try {
			session.createSQLQuery("update TB_USER_DEPT  set A = 1 where UD_ID =:did").setString("did", deptId).executeUpdate();
		//	session.createQuery("delete from Dept d where d.DId =:did").setString("did", deptId).executeUpdate();
			
			tx.commit();
			log.debug("delete successful");
		} catch (RuntimeException re) {
			tx.rollback();
			log.error("delete failed", re);
			throw re;
		}
		session.close();
	}
	
	private void accessDeptDIf(List<String> DIds, int value) throws Exception {
		Session session = null;
		Transaction tx = null;
		String hql = "update UserDept d set d.udIf = " + value + "where d.udId = :DId";
		try {
			session = this.getSessionFactory().openSession();
			tx = session.beginTransaction();
			for(String DId:DIds) {
				Query query = session.createQuery(hql);
				query.setString("DId", DId);
				
				query.executeUpdate();
			}
			//System.out.println("**************" + "Betch Update!!");
			tx.commit();
		} catch (Exception e) {
			if(tx != null) {
				tx.rollback();
			}
			throw e;
		}finally {
			if(session != null) {
				session.close();
			}
		}
	}

	public List<UserDept> findByDeptTypeId(String deptTypeId) {
		List<UserDept> result=null;
		Session session = this.getSessionFactory().openSession();
		result = session.createSQLQuery("select * from TB_USER_DEPT t where t.UD_TYPE =:deptType").addEntity(UserDept.class).setString("deptType", deptTypeId).list();
		session.close();
		return result;
	}
	
	public UserDept merge(UserDept detachedInstance) {
		log.debug("merging TbEventPlan instance");
		try {
			UserDept result = (UserDept) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}
	
	public void addBelongDept(UserDeptContact user,UserDept userDept){
		Session session = null;
		try{
			session = this.getSession(true);
			
			session.refresh(userDept);
			session.refresh(user);
			userDept.getTbUsers().add(user);
			session.merge(userDept);
			session.flush();
			session.clear();
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(session != null){
				session.close();
			}
		}
	}
}
